package com.quasar.hpatient.module.home;

import android.Manifest;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.bean.home.HomeBean;
import com.quasar.hpatient.bean.home_inspection.InspectionBean;
import com.quasar.hpatient.bean.home_medicine.MedicineTodayBean;
import com.quasar.hpatient.dialog.AlertDialog;
import com.quasar.hpatient.module.comm_main.MainActivity;
import com.quasar.hpatient.module.comm_qrcode.QrcodeActivity;
import com.quasar.hpatient.module.comm_web.WebActivity;

import java.util.ArrayList;
import java.util.List;

import lib.quasar.base.frame.BaseFragment;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.permission.annotation.PermissionAgain;
import lib.quasar.permission.annotation.PermissionDenied;
import lib.quasar.permission.annotation.PermissionFail;
import lib.quasar.permission.annotation.PermissionSucc;
import lib.quasar.permission.core.PermissionManager;
import lib.quasar.permission.core.intent.IntentType;
import lib.quasar.qrcode.ZxingConfig;
import lib.quasar.qrcode.ZxingManager;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.util.GlideUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.util.ToastUtil;
import lib.quasar.widget.banner.BannerLayout;

/**
 * description: 首页
 * created by kalu on 2018/3/19 16:14
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements HomeView {

    private RecyclerView recycler;
    @Override
    public int initView() {
        return R.layout.fragment_home;
    }

    @Override
    public void initDataLocal() {

        getView().findViewById(R.id.fragment_home_search).setOnClickListener(v -> ToastUtil.showToast("点击搜搜"));
        getView().findViewById(R.id.fragment_home_qrcode).setOnClickListener(v -> cameraPermission());

        recycler = getView().findViewById(R.id.fragment_home_recycler);
        getPresenter().initList(this, recycler);
        getPresenter().initMessageBroadcast(this, recycler);
    }

    @Override
    public void initDataNet() {
        //final RecyclerView recycler = getView().findViewById(R.id.fragment_home_recycler);
        getPresenter().bannerList(this);
        getPresenter().medicineList(this, recycler, false);
    }

    @Override
    public void onResume() {
        //final RecyclerView recycler = getView().findViewById(R.id.fragment_home_recycler);
        getPresenter().refreshMessage(this, recycler);
        getPresenter().medicineList(this, recycler, true);
        super.onResume();
    }

    @Override
    public void showWarning() {
        if (getPresenter().isDoseAll()){
            toast("药品已经全部服用！");
            return;
        }

        final AlertDialog dialog = new AlertDialog(getActivity());
        dialog.show();
        dialog.setMiddleGone();
        dialog.setTopTitles("确定药物已全部服用？");
        dialog.setTitles("注：确认后，\r\n您还可以到当天的服药记录中进行详细修改！");
        dialog.setButton("否", "是");
        dialog.setOnDialogChangeListener((left, right) -> {
            if (left) {


            } else if (right) {

                getPresenter().editMedicineOral(this,recycler,-1,4);
            }
        });
    }


    @Override
    public void showHint(int position,int flag) {

        MedicineTodayBean.ItemBean bean = getPresenter().getHomeBean(position).getMedicine();
        if (null == bean)
            return;
        String unit = bean.getDose_name();
        String[] split = unit.split("/");
        String unitend = "";
        if (null != split && split.length == 2) {
            unitend+=split[1];
        }
        String title = "药品名称："+bean.getMname()+"\r\n"+"药品规格："+unit+"\r\n"+"本次用量："+bean.getUse_number()+unitend+"\r\n"+"应服药时间："+bean.getMedicineTime();
        final AlertDialog dialog = new AlertDialog(getActivity());
        dialog.show();
        switch (flag){
            case -1:
                dialog.setTopTitles("你确定要服药了吗 ？(你已提前)");
                break;
            case 1:
                dialog.setTopTitles("你确定要服药了吗 ？(你已超时)");
                break;
            case 0:
            default:
                dialog.setTopTitles("你确定要服药了吗 ？");
                dialog.setMiddleGone();
        }

        dialog.setTitles(title);
        dialog.setButton("否", "是");
        dialog.setOnDialogChangeListener((left, right) -> {
            if (left) {


            } else if (right) {

                getPresenter().editMedicineOral(this,recycler,position,1);
            }else{
                getPresenter().editMedicineOral(this,recycler,position,3);
            }
        });
    }


    @Override
    public void setBanner(List<String> list) {

        if (null == getView() || null == list || list.size() == 0) return;

        final RecyclerView recycler = getView().findViewById(R.id.fragment_home_recycler);
        if (null == recycler) return;

        RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter || !(adapter instanceof BaseCommonAdapter)) return;

        LinearLayout head = ((BaseCommonAdapter) adapter).getHead();
        BannerLayout banner = head.findViewById(R.id.fragment_home_type1_banner);
        if (null == banner) return;

        banner.notifyDataSetChanged(list);
        banner.setOnBannerChangeListener(new BannerLayout.OnBannerImageChangeListener() {

            @Override
            public void onBannerCreate(ImageView image, String imageUrl) {
                GlideUtil.loadImageSimple(BaseApp.getContext(), image, imageUrl);
            }

            @Override
            public void onBannerCilck(int position) {
                Intent intent = new Intent(BaseApp.getContext(), WebActivity.class);
                intent.putExtra(WebActivity.WEB_URL, "www.baidu.com");
                goNext(intent);
            }
        });
    }

    @Override
    public void cameraPermission() {
        PermissionManager.get(HomeFragment.this)
                .setForce(true)
                .setPermissionName(Manifest.permission.CAMERA)
                .setRequestCode(BaseConstant.PERMISSION_CAMERA)
                .setPageType(IntentType.GOOGLE_SETTING)
                .request();
    }

    @Override
    public void minusBadgeNumber(int badgeNumber) {
        final FragmentActivity activity = getActivity();
        if (!(activity instanceof MainActivity))
            return;
        ((MainActivity) activity).minusBadgeNumber(badgeNumber);
    }

    @PermissionSucc(BaseConstant.PERMISSION_CAMERA)
    public void cameraSucc(int code, List<String> list) {
        LogUtil.e("dsds", "cameraSucc ==> code = " + code);

        ToastUtil.showToast("获取相机权限成功");
        ZxingConfig scanConfig = new ZxingConfig.Builder()
                //设置完成震动
                .isShowVibrate(true)
                //扫描完成声音
                .isShowBeep(true)
                //显示相册功能
                .isShowPhotoAlbum(true)
                //自定义文案
                .setScanHintText(getResources().getString(R.string.comm_qrcode_hint))
                //扫描线的颜色
                .setScanColor(getResources().getColor(R.color.color_bg_theme))
                .builder();
        ZxingManager.startScan(getActivity(), 1000, scanConfig, QrcodeActivity.class);
    }

    @PermissionFail(BaseConstant.PERMISSION_CAMERA)
    public void cameraFail(int code, List<String> list) {
        LogUtil.e("dsds", "cameraFail ==> code = " + code);
        ToastUtil.showToast("获取相机权限失败");
    }

    @PermissionAgain(BaseConstant.PERMISSION_CAMERA)
    public void cameraAgain(int code, List<String> list) {
        LogUtil.e("dsds", "cameraAgain ==> code = " + code);
    }

    @PermissionDenied(BaseConstant.PERMISSION_CAMERA)
    public void onDenied(int code, List<String> list, Intent intent) {
        LogUtil.e("dsds", "onDenied ==> code = " + code);
        ToastUtil.showToast("获取相机权限, 用户已拒绝");
        goNext(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionManager.onRequestPermissionsResult(getActivity(), requestCode, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {
            if (data == null) {
                return;
            }
            switch (resultCode) {
                case QrcodeActivity.RESULT_SUCCESS:
                    String resultSuccess = data.getStringExtra(ZxingManager.INTENT_KEY_RESULT_SUCCESS);
                    toast(resultSuccess);
                    break;
                case QrcodeActivity.RESULT_FAIL:
                    String resultError = data.getStringExtra(ZxingManager.INTENT_KEY_RESULT_ERROR);
                    toast(resultError);
                    break;
                case QrcodeActivity.RESULT_CANCLE:
                    toast("取消扫码");
                    break;
            }
        }
    }


}